package com.m4399.minigamedemo

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import com.m4399.minigamedemo.LoginHelper.setLoginInfo
import com.m4399.minigame.sdk.MiniSDK
import com.pm.api.AppManagerHelper
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

class MainActivity : Activity() {
    private val sp by lazy { this.getSharedPreferences("config", 0) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //默认有个内置版本，正常接入不要调用
       // loadNestedRuntime()
    }


    override fun onResume() {
        super.onResume()
        initTestConfig()
        refreshVersionInfo()
    }

    private fun refreshVersionInfo() {
        findViewById<TextView>(R.id.tvVersionInfo).text = "线上Runtime" + ",  \truntime 版本:${AppManagerHelper.INSTANCE.getPackageInfo(MiniSDK.RUNTIME_PACKAGE_NAME).versionName}" + ",  \tapi 版本:${AppManagerHelper.INSTANCE.getPackageInfo("com.minigame.sdk.api").versionName}"
    }

    /**
     * 初始化环境选择和模式选择的View
     */
    private fun initTestConfig() {
        initEnvAndMode(R.id.env_group, "env", "test")
        initEnvAndMode(R.id.mode_group, "mode", "pub")

        //将SP里面的数据都填入'MiniSDK.config'中
        for (field in MiniSDK.config.javaClass.declaredFields) {
            val name = field.name
            if (sp.contains(name)) {
                MiniSDK.config.set(name, sp.all.get(name)!!)
            }
        }

    }


    /**
     * 初始化环境选择和模式选择的View
     */
    private fun initEnvAndMode(groupId: Int, spKey: String, defaultValue: String = "") {
        findViewById<RadioGroup>(groupId).apply {
            if (!sp.contains(spKey)) {
                sp.edit().putString(spKey, defaultValue).commit()
            }
            val envValue = sp.getString(spKey, defaultValue)!!
            for (i in 0 until childCount) {
                val childAt = getChildAt(i)
                if (childAt is RadioButton && envValue.isNotEmpty()) {
                    childAt.isChecked = childAt.text == envValue
                }
            }
            setOnCheckedChangeListener { rg, checkedId ->
                sp.edit().putString(spKey, findViewById<RadioButton>(checkedId).text.toString()).apply()
                initTestConfig()
            }
        }
    }


    fun startGame(view: View?) {
        val idText = findViewById<EditText>(R.id.game_id).text.toString()
        if (idText.isEmpty()) {
            Toast.makeText(this, "id不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        start(idText)
    }

    fun deleteRuntime(view: View?) {
        MiniSDK.clearRuntimeEnv()
        AppManagerHelper.INSTANCE.uninstall(MiniSDK.RUNTIME_PACKAGE_NAME)
        AppManagerHelper.INSTANCE.uninstall("com.minigame.sdk.api")
        refreshVersionInfo()
    }

    fun loadNestedRuntime() {
        val outputFile = File(filesDir, "com.minigame.sdk.runtime.apk")
        Log.d("outputFile =", "updateRuntime: outputFile $outputFile")
        outputFile.delete()
        outputFile.outputStream().use {
            assets.open("com.minigame.sdk.runtime.apk").copyTo(it)
        }
        AppManagerHelper.INSTANCE.install(MiniSDK.RUNTIME_PACKAGE_NAME, outputFile.absolutePath)
        refreshVersionInfo()
    }

    private fun start(id: String, extra: Bundle = Bundle()) {
        GlobalScope.launch {
            try {
                MiniGameApplication.currentId = id
                setLoginInfo()
                MiniSDK.startMiniById(this@MainActivity, id, extra)
            } catch (e: Throwable) {
                runOnUiThread {
                    Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_SHORT).show()
                }
            }

        }
    }


}